<template>
  <div class="payment">
    <div class="header">
      <span class="title">待付款</span>
    </div>
    <div class="address">
      <div class="address-box" @click="gotos()">
        <div class="address-icons">
          <img :src="images8" class="images8">
        </div>
        <div class="address-name">
          收货人：{{receiveAddrs.receiveName}}{{data.receiveName}}
          <span
            class="phone"
          >{{receiveAddrs.receivePhone}}{{data.receivePhone}}</span>
        </div>
        <div class="address-place">{{receiveAddrs.receiveAddr}}{{data.receiveAddr}}</div>
        <div class="address-iconsright">
          <img :src="images5" class="images5">
        </div>
      </div>
    </div>
    <div class="body-top">
      <span class="icon-pic">
        <img :src="images9" class="images9">
      </span>
      <span class="companyname">华夏黉</span>
    </div>
    <div class="paymentgoods" v-for="(list,index) in shoppingCarts" :key="list.id"  >
      <div class="paymentgoods-box">
        <div class="paymentgoods-picture">
          <img :src="JSON.parse(list.goodsPic)" class="imgs">
        </div>
        <div class="paymentgoods-title">
          <div class="paymentgoods-title-introduce">{{list.goodsName}}{{list.goodsIntro}}</div>
          <div class="paymentgoods-title-category">{{value}}</div>

          <div class="num">X{{list.buyNum}}</div>
          <div class="selection-component" v-if="showsss">
            <div class="selection-show" @click="toggleDrop(index)">
              <span>{{list.isStyle.dealModeName}}</span>
              <!-- <span v-else>{{ selections[nowIndex].dealModeName}}</span> -->
              <div class="arrow"></div>
            </div>
            <div class="selection-list" v-if="isDrop==index">
              <ul>
                <li
                  v-for="(item, _index) in selections"
                  @click="chooseSelection(item,index,list.shoppingCartId)"
                  class="lis"
                  :key="item._index"
                >{{ item.dealModeName }}</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <div class="blanks"></div>
    </div>
    <div class="weixinpay">
      <span class="weixinpay-left">
        <span class="icon">
          <img :src="images10" class="images10">
        </span>微信支付
      </span>
    </div>
    <!-- <div class="leavemessage">
      <span class="leavemessage-left">买家留言：</span>
      <span class="leavemessage-right">
        <textarea type="text" placeholder="选填：填写内容为您想告诉卖家的需求哦~" class="int"></textarea>
      </span>
    </div>-->
    <div class="bottom">
      <div class="btnleft">
        实付款：
        <span class="price">￥{{totaleprice || data.totaleprice ||toatlprice}}</span>
      </div>
      <div class="btnright" @click="wxpaymoney">立即付款</div>
    </div>
  </div>
</template>

<script>
import pic4 from "../../icons/left2.png";
import pic5 from "../../icons/right.png";
import pic8 from "../../icons/address.png";
import pic9 from "../../icons/shop.png";
import pic10 from "../../icons/weixin.png";
import * as api from "../../request/api.js";
export default {
  name: "payment",

  data() {
    return {
      images4: pic4,
      images5: pic5,
      images8: pic8,
      images9: pic9,
      images10: pic10,
      isDrop: -1,
      nowIndex: 0,
      dealModeId: "",
      ids: [],
      id: "",
      dealid: "",
      receiveAddrs: "",
      shoppingCarts: [null],
      selections: [null],
      shoppingid: "",
      value: "",
      idss: [],
      totaleprice: 0,
      showsss: true,
      data: "",
      receiveAddrId: "",
      showmore: true,
      xcq: "999",
      toatlprice:''
    };
  },
  created() {
    this.selections=this.$route.query.dealModeName
    this.shoppingCarts = JSON.parse(sessionStorage.getItem("shoppingCarts"));
    this.selections = JSON.parse(sessionStorage.getItem("selection"));
    // if(this.shoppingCarts!=null){
    //   this.shoppingCarts.map(a => {
    //         a.isStyle = {
    //           dealModeName: "配送方式"
    //         };
    //       })
    // } 
    this.$route.query; //这里接收购物车传的ids
    this.data = this.$route.query;
    console.log(this.shoppingCarts)
    this.receiveAddrId = this.$route.query.id;
    // alert( this.$route.query.receiveName)
    // console.log(this.$route.query,this.receiveAddrId);
    this.ids = this.$route.query.ids;
    this.toatlprice=this.$route.query.toatlprice
    this.totaleprice = this.$route.query.totaleprice;
    console.log(this.$route.query,this.selections, "xcqx8888q",);
    //  console.log(this.$route.query.totaleprice)
    if (this.ids == undefined) {
      // console.log(98989898989898);
      return false;
    } else {
      this.$http({
        method: "post",
        url: api.WAITPAY,
        data: {
          ids: this.ids //请求  我如果把这个ids存了，格式会变。
        } //wo qu 我去
      })
        .then(resp => {
          // console.log(resp.data.data.shoppingCarts);
          this.shoppingCarts = resp.data.data.shoppingCarts;
          this.shoppingCarts.map(a => {
            a.isStyle = {
              dealModeName: "配送方式"
            };
          });
          sessionStorage.setItem(
            "shoppingCarts",
            JSON.stringify(resp.data.data.shoppingCarts)
          );
          this.receiveAddrs = resp.data.data.receiveAddrs;
          this.receiveAddrId = resp.data.data.receiveAddrs.id;
          console.log(this.shoppingCarts);
          resp.data.data.shoppingCarts.forEach(items => {
            this.shoppingid = items.shoppingCartId;
            this.selections = items.dealModes;
            sessionStorage.setItem(
              "selection",
              JSON.stringify(items.dealModes)
            );
            // this.totalprice += (items.goodsTruePrice/100)*items.buyNum
            console.log(this.totaleprice);
            items.goodsAttrSpecInfo.forEach(item1 => {
              this.value = item1.value;
            });
          });
        })
        .catch(resp => {});
    }

    // console.log(this.selections)
    // if (this.selections.length == 0) {
    //   this.showsss = false;
    // } else {
    //   this.showsss = true;
    // }
  },
  mounted() {
    this.shoppingCarts.forEach(itemss => {
      console.log(itemss)
      this.shoppingid = itemss.shoppingCartId; 
      //这里不是字符串拼接吗  要不你这些遍历没有意义 这是切换地址后需要。不然会消失  那这只会是最后一个商品的id
    });
  },
  methods: {
    gotos() {
      console.log(this.totaleprice);
      const totaleprice = this.totaleprice;
      const dealModeName = this.selections;
      this.$router.push({
        path: "/chooseaddress", //在哪
        query: {
          totaleprice,
          dealModeName
        }
      });
    },
    goback() {
      this.$router.go(-1);
    },
    toggleDrop(index) {
      // console.log(index)
      this.isDrop = index;
      // this.isDrop = !this.isDrop;
    },
    chooseSelection(item, b, shoppingCartId) {
      console.log(item, b, "xcq");
      // this.isDrop = false;
      this.isDrop = -1;
      //this.showmore=false
      this.shoppingCarts[b].isStyle = { shoppingCartId, ...item };
      sessionStorage.setItem(
        "shoppingCarts",
        JSON.stringify(this.shoppingCarts)
      );
      console.log("xcq", this.selections[this.nowIndex]);
      this.$emit("on-change", this.selections[this.nowIndex]);

      this.dealModeId = this.selections[this.nowIndex].id;
      // console.log(this.dealModeId);
    },
    wxpaymoney() {
      //  function isWeiXin() {
      //      //此处是一段ua判断
      //         var ua = window.navigator.userAgent.toLowerCase();
      //         console.log(ua);
      //         if (ua.match(/MicroMessenger/i) == "micromessenger") {
      //           return true;
      //         } else {
      //           return false;
      //         }
      //       }
      // if (isWeiXin()) {
      // alert("微信"); 根据前面的此处可以判断是在微信内打开的
      //后端返回所需数据
      // alert(location.href);
      var that = this;
      let shoppingCartItems = this.shoppingCarts.reduce((result, item) => {
        result.push({
          dealModeId: item.isStyle.id,
          id: item.isStyle.shoppingCartId
        });
        return result;
      }, []);

      this.$http({
        method: "post",
        url: api.GOPAYJSAPI,
        data: {
          receiveAddrId: this.receiveAddrId, //地址id
          shoppingCartItems
        }
      })
        .then(res => {
          //  alert(JSON.stringify(res),'aa');
          console.log(res);
          var that = this;
          if (res.data.success == true) {
            // const pay_params = JSON.parse(params);
            var str =
              "appId=" +
              res.data.data.appId +
              "&timeStamp=" +
              res.data.data.timeStamp +
              "&nonceStr=" +
              res.data.data.nonceStr +
              "&prepay_id=" +
              res.data.data.packageA +
              "&signType=" +
              res.data.data.signType +
              "&paySign=" +
              res.data.data.sign;
            // console.log(str);
            WeixinJSBridge.invoke(
              "getBrandWCPayRequest",
              {
                appId: res.data.data.appId, //公众号名称，由商户传入
                timeStamp: res.data.data.timeStamp, //时间戳，自1970年以来的秒数
                nonceStr: res.data.data.nonceStr, //随机串
                package: res.data.data.packageA,
                signType: res.data.data.signType, //微信签名方式：
                paySign: res.data.data.sign //微信签名sign
              },
              function(res) {
                // alert(res.err_msg);
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                  //此处是调起微信支付成功的回调，可以在此处跳转支付成功的页面，和你的业务逻辑
                  that.paymentData = "支付成功";
                  that.$router.push({ path: "/paysuccess" });
                  // 使用以上方式判断前端返回,微信团队郑重提示：
                  //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                  //此处是调起取消微信支付的回调，可以在此处跳转您已取消支付的页面，和你的业务逻辑
                } else if (res.err_msg == "get_brand_wcpay_request:fail") {
                  //此处是调起微信支付失败的回调
                }
                // alert(res.err_msg, "aa");
                // alert(JSON.stringify(res)); //此处可以弹出调起微信支付的失败或成功的信息
              }
            );
          }
        })
        .catch(function(error) {
          // alert(error);
        });
      // } else {
      //   // alert('微信外')  根据前面的ua判断，可以判断出是在微信外调起的微信支付
      //   //向后台请求相关的数据
      //   // this.$axios({
      //   //     method: "post",
      //   //     url: "", 你的接口地址
      //   //     headers: {'Content-Type': 'application/x-www-form-urlencoded'}
      //   //   })
      //   //   .then(res => {
      //   //       console.log(res)
      //   //   })
      //   // console.log(this.$refs.link)  返回支付路径
      //   // this.$refs.link.href = "";   跳转支付页面
      // }
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../less/payment.less";
</style>
